package com.taxshare.seller.util;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.taxshare.freemark.utils.FreemarkUtil;
import com.taxshare.seller.entity.EquipmentEntity;
import com.taxshare.seller.service.EquipmentService;
import com.taxshare.seller.view.vo.GlobalInfoVO;
import com.taxshare.tools.util.Base64Util;
import com.taxshare.tools.util.UUIDUitl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static cn.hutool.core.util.NumberUtil.*;

/**
 * @Author: scl
 * @Date: 2018-11-19 14:52
 */
@Slf4j
@Component
public class InvoiceHelper {

    private static final String ACCOUNTID_PREFIX = "S";

    private static final int ACCOUNTID_LENTH = 19;

    private static final String RED_FLAG = "信息表编号";

    private static final Pattern REDNO_IS_NUM = Pattern.compile("\\d{16}");

    @Autowired
    private EquipmentService equipmentService;

    private static InvoiceHelper invoiceHelper;

    /**
     * 税神通销项数据下载接口：发票状态为
     * 0：已开具的正数发票
     * 1：已开具的负数发票
     * 2：未开具发票的作废发票
     * 3：作废票
     * <p>
     * 需转为平台相应的状态
     * 0-正常，
     * 1-作废，
     * 2-红冲，
     * 3-失控，
     * 4-异常
     *
     * @param invoiceStatus
     * @return
     */
    public static int transInvoiceStatusBySstOut(String invoiceStatus) {
        if ("0".equals(invoiceStatus) || "1".equals(invoiceStatus)) {
            return 0;
        }
        if ("2".equals(invoiceStatus) || "3".equals(invoiceStatus) || "4".equals(invoiceStatus)) {
            return 1;
        }
        return -1;
    }

    /**
     * 百分数转小数
     *
     * @param str
     * @return
     */
    public static String transPercentToDecimal(String str) {
        String[] split = str.split("%");
        String d = split[0];
        Double aDouble = Double.valueOf(d);
        Double dec = div(aDouble, new Double(100));
        return String.valueOf(dec);
    }

    /**
     * 从发票备注里取出对账单号
     *
     * @param remark
     * @return
     */
    public static String getAccountIdFromRemark(String remark) {
        try {
            String accountId = "";
            int s = appearNumber(remark, ACCOUNTID_PREFIX);
            if (s == 1) {
                int start = remark.indexOf(ACCOUNTID_PREFIX);
                int end = start + ACCOUNTID_LENTH;
                accountId = remark.substring(start, end);
            }
            return accountId;
        } catch (Exception e) {
            log.info("未能截取到对账单单号，发票备注栏: " + remark);
            return null;
        }
    }

    /**
     * 从发票备注里取出红字编码
     *
     * @param remark
     * @return
     */
    public static String getRedNoFromRemark(String remark) {
        try {
            String str = remark.replaceAll(" ", "");
            if (StringUtils.isNotBlank(str)) {
                if (str.contains(RED_FLAG)) {
                    int startIdx = str.indexOf(RED_FLAG) + 5;
                    String numStr = str.substring(startIdx);
                    String[] split = numStr.split("");
                    int i = 0;
                    for (String s : split) {
                        try {
                            Integer.parseInt(s);
                            // 正常解析数字
                            startIdx += i;
                            String substring = str.substring(startIdx, 16 + startIdx);
                            Matcher isNum = REDNO_IS_NUM.matcher(substring);
                            if (isNum.matches()) {
                                return substring;
                            } else {
                                return "";
                            }
                        } catch (NumberFormatException e) {
                            i++;
                            continue;
                        }
                    }
                } else {
                    return "";
                }
            } else {
                return "";
            }
        } catch (Exception e) {
            log.info("未能截取到红字信息表编号，发票备注栏: " + remark);
            return "";
        }
        return "";
    }

    static int appearNumber(String srcText, String findText) {
        int count = 0;
        Pattern p = Pattern.compile(findText);
        Matcher m = p.matcher(srcText);
        while (m.find()) {
            count++;
        }
        return count;
    }

    /*
     *同步发票类型转换
     * 由盘入库
     */
    public static String ptransFplxdm(String fplxdm) {
        if ("0".equals(fplxdm)) {
            fplxdm = "004";
        } else if ("2".equals(fplxdm)) {
            fplxdm = "007";
        } else if ("51".equals(fplxdm)) {
            fplxdm = "026";
        } else if ("41".equals(fplxdm)) {
            fplxdm = "011";
        }
        return fplxdm;
    }

    /*
     *特殊票种类型转换
     * 由盘入库
     */
    public static String ptransTspz(String tspz) {
        if ("0".equals(tspz)) {
            tspz = "00";
        } else if ("14".equals(tspz)) {
            tspz = "08";
        } else if ("9".equals(tspz)) {
            tspz = "02";
        } else if ("8".equals(tspz)) {
            tspz = "01";
        } else {
            tspz = "00";
        }
        return tspz;
    }


    /*
     *特殊票种类型转换
     * 由库开票
     */
    public static String transTspz(String plx, String tspz) {

        if ("jsp".equals(plx)) {
            if ("00".equals(tspz)) {
                tspz = "0";
            } else if ("08".equals(tspz)) {
                tspz = "14";
            } else if ("02".equals(tspz)) {
                tspz = "9";
            } else if ("01".equals(tspz)) {
                tspz = "8";
            } else {
                tspz = "0";
            }

        }

        return tspz;
    }


    /*
     *发票类型转换
     * 由库到盘
     */
    public static String transFplxdm(String plx, String fplxdm) {
        if ("jsp".equals(plx)) {
            if ("004".equals(fplxdm)) {
                fplxdm = "0";
            }
            if ("007".equals(fplxdm)) {
                fplxdm = "2";
            }
            if ("026".equals(fplxdm)) {
                fplxdm = "51";
            }
        }
        return fplxdm;
    }

    public static String transFplxdm(String fplxdm) {
        if ("004".equals(fplxdm)) {
            fplxdm = "0";
        }
        if ("007".equals(fplxdm)) {
            fplxdm = "2";
        }
        if ("026".equals(fplxdm)) {
            fplxdm = "51";
        }
        return fplxdm;
    }

    /**
     * 调用接口头返回信息
     *
     * @param data
     * @param interfaceCode
     * @param sellerTaxNo
     * @return
     */
    public static String getXmlData(String data, String interfaceCode, String sellerTaxNo, String dataExchangeId) {
        String content = Base64Util.encode(data);
        GlobalInfoVO globalInfoVO = new GlobalInfoVO();
        globalInfoVO.setContent(content);
        globalInfoVO.setInterfaceCode(interfaceCode);
        globalInfoVO.setUserName(sellerTaxNo);
        QueryWrapper<EquipmentEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("seller_tax_no",sellerTaxNo)
                .eq("equipment_mode","4");
        EquipmentEntity entity = invoiceHelper.equipmentService.getOne(queryWrapper);
        if (entity == null) {
            return null;
        }
        globalInfoVO.setFjh(entity.getExtensionNumber() + "-" + entity.getTerminalNumber());
        if (StrUtil.isNotBlank(dataExchangeId)) {
            globalInfoVO.setDataExchangeId(dataExchangeId);
        } else {
            globalInfoVO.setDataExchangeId(UUIDUitl.UUID16(false));
        }

        String xmlData = FreemarkUtil.getTemplateObj("head.ftl", globalInfoVO);
        return xmlData;
    }

    @PostConstruct
    public void init() {
        invoiceHelper = this;
        invoiceHelper.equipmentService = this.equipmentService;
    }
}
